package conf

import (
	"fmt"
	"os"
	"path/filepath"
)

// 新建一个结构体来存储路径
type pathConfig struct {
	confPath string
}

func NewPathConfig(confPath string) *pathConfig {
	confPath = filepath.Join(confPath, "conf")
	return &pathConfig{
		confPath: confPath,
	}
}

// 寻找mod文件
func hasGoMod(dir string) bool {
	goModPath := filepath.Join(dir, "go.mod")
	if _, err := os.Stat(goModPath); err == nil {
		return true
	}
	return false
}

// 寻找项目根路径
func getProjectRoot() (string, error) {
	currentDir, err := os.Getwd()
	if err != nil {
		return "", err
	}
	for {
		if hasGoMod(currentDir) {
			return currentDir, nil
		}
		parent := filepath.Dir(currentDir)
		if parent == currentDir {
			break
		}
		currentDir = parent
	}
	return "", fmt.Errorf("go module not found in the current directory or any parent directory")
}

// 返回路径配置的结构体函数
func ReturnConfig() *pathConfig {
	root_path, err := getProjectRoot()
	if err != nil {
		panic(err)
	}
	p := NewPathConfig(root_path)
	return p
}
